import React from 'react'

import { Container } from './style'

import moment from 'moment'

interface Props {
    endDate: string,
    timeout: any
}
interface State {
    now: any
}
let timer: any = null
class CountDown extends React.Component<Props, State>{
    readonly state: Readonly<State> = {
        now: moment()
    }

    componentDidMount(){
        timer = setInterval((): void => {
            this.setState({
                now: moment()
            })
        }, 1000)
    }
    componentWillUnmount(){
        clearInterval(timer)
    }
    

    get countDown(){
        return (endDate: string): string => {
            let m1: any = this.state.now
            let m2: any = moment(endDate)
            let du = moment.duration(m2 - m1, 'ms')
            let hours = du.get('hours')
            let mins = du.get('minutes')
            let ss = du.get('seconds')
            if (hours <= 0 && mins <= 0 && ss <= 0) {
                this.props.timeout()
                return "今日已结束"
            } else {
                return `${this.PrefixInteger(hours, 2)} <span style="font-size: 16px;">小时</span> ${this.PrefixInteger(mins, 2)} <span style="font-size: 16px;">分钟</span><span style="color: #F56C6C;"> ${this.PrefixInteger(ss, 2)} </span><span style="font-size: 16px;">秒</span>`
            }
        }
    }

    //数字前补 0 
    // num传入的数字，n需要的字符长度
    PrefixInteger(num: number, n: number): string {
        return (Array(n).join('0') + num).slice(-n)
    }

    render(): any{
        return (
            <Container dangerouslySetInnerHTML={{ __html: this.countDown(this.props.endDate)}}></Container>
        )
    }
}

export default CountDown